# coding=utf-8
# !/usr/bin/python
import sys, math, json, time
from pprint import pprint

sys.path.append('..')
from base.spider import Spider
from urllib.parse import quote
from urllib.parse import urlencode

class Spider(Spider):  # 元类 默认的元类 type
    site_name = 'xk_豆瓣'
    #douban_api_host = 'https://api.douban.com/api/v2'
    douban_api_host = 'https://frodo.douban.com/api/v2'
    header = {
        "Host": "frodo.douban.com",
        "Connection": "Keep-Alive",
        "Referer": "https://servicewechat.com/wx2f9b06c1de1ccfca/84/page-frame.html",
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat"
    }
    miniapp_apikey = "0ac44ae016490db2204ce0a042db2916"
    count = 20
    img_source = '@Referer=https://frodo.douban.com/@User-Agent=Mozilla/5.0%20(Windows%20NT%2010.0;%20Win64;%20x64)%20AppleWebKit/537.36%20(KHTML,%20like%20Gecko)%20Chrome/113.0.0.0%20Safari/537.36'
    classes = [
        {'type_name': '热门电影', 'type_id': 'hot_gaia'},
        {'type_name': '热播剧集', 'type_id': 'tv_hot'},
        {'type_name': '热播综艺', 'type_id': 'show_hot'},
        {'type_name': '电影筛选', 'type_id': 'movie'},
        {'type_name': '电视筛选', 'type_id': 'tv'},
        {'type_name': '电影榜单', 'type_id': 'rank_list_movie'},
        {'type_name': '电视榜单', 'type_id': 'rank_list_tv'}
    ]
    filters = {
        'hot_gaia':[
            {
                'key':'sort',
                'name':'排序',
                'value':[
                    {'n':'热度','v':'recommend'},
                    {'n':'最新','v':'time'},
                    {'n':'评分','v':'rank'}
                ]
            },
            {
                'key':'area',
                'name':'地区',
                'value':[{'n': i, 'v': i} for i in '全部#华语#欧美#韩国#日本'.split('#')]
            }
        ],
        'tv_hot':[
            {
                'key':'type',
                'name':'分类',
                'value':[
                    {'n':'综合','v':'tv_hot'},
                    {'n':'国产剧','v':'tv_domestic'},
                    {'n':'欧美剧','v':'tv_american'},
                    {'n':'日剧','v':'tv_japanese'},
                    {'n':'韩剧','v':'tv_korean'},
                    {'n':'动画','v':'tv_animation'}
                ]
            }
        ],
        'show_hot':[
            {
                'key':'type',
                'name':'分类',
                'value':[
                    {'n':'综合','v':'show_hot'},
                    {'n':'国内','v':'show_domestic'},
                    {'n':'国外','v':'show_foreign'}
                ]
            }
        ],
        'movie':[
            {
                'key':'类型',
                'name':'类型',
                'value':[{'n':'全部类型','v':''}] + [{'n': i, 'v': i} for i in '喜剧#爱情#动作#科幻#动画#悬疑#犯罪#惊悚#冒险#音乐#历史#奇幻#恐怖#战争#传记#歌舞#武侠#情色#灾难#西部#纪录片#短片'.split('#')]
            },
            {
                'key':'地区',
                'name':'地区',
                'value':[{'n':'全部地区','v':''}] + [{'n': i, 'v': i} for i in '华语#欧美#韩国#日本#中国大陆#美国#中国香港#中国台湾#英国#法国#德国#意大利#西班牙#印度#泰国#俄罗斯#加拿大#澳大利亚#爱尔兰#瑞典#巴西#丹麦'.split('#')]
            },
            {
                'key':'sort',
                'name':'排序',
                'value':[
                    {'n':'近期热度','v':'T'},
                    {'n':'首映时间','v':'R'},
                    {'n':'高分优先','v':'S'}
                ]
            },
            {
                'key':'年代',
                'name':'年代',
                'value':[{'n':'全部年代','v':''}] + [{'n':str(i), 'v':str(i)} for i in range(int(time.localtime().tm_year), 2018, -1)] + [
                    {'n':'2010年代','v':'2010年代'},
                    {'n':'2000年代','v':'2000年代'},
                    {'n':'90年代','v':'90年代'},
                    {'n':'80年代','v':'80年代'},
                    {'n':'70年代','v':'70年代'},
                    {'n':'60年代','v':'60年代'},
                    {'n':'更早','v':'更早'}
                ]
            }
        ],
        'tv':[
            {
                'key':'类型',
                'name':'类型',
                'value':[{'n':'不限','v':''}] + [{'n': i, 'v': i} for i in '电视剧#综艺'.split('#')]
            },
            {
                'key':'电视剧形式',
                'name':'电视剧形式',
                'value':[{'n':'不限','v':''}] + [{'n': i, 'v': i} for i in '喜剧#爱情#悬疑#动画#武侠#古装#家庭#犯罪#科幻#恐怖#历史#战争#动作#冒险#传记#剧情#奇幻#惊悚#灾难#歌舞#音乐'.split('#')]
            },
            {
                'key':'综艺形式',
                'name':'综艺形式',
                'value':[{'n':'不限','v':''}] + [{'n': i, 'v': i} for i in '真人秀#脱口秀#音乐#歌舞'.split('#')]
            },
            {
                'key':'地区',
                'name':'地区',
                'value':[{'n':'全部地区','v':''}] + [{'n': i, 'v': i} for i in '华语#欧美#国外#韩国#日本#中国大陆#中国香港#美国#英国#泰国#中国台湾#意大利#法国#德国#西班牙#俄罗斯#瑞典#巴西#丹麦#印度#加拿大#爱尔兰#澳大利亚'.split('#')]
            },
            {
                'key':'sort',
                'name':'排序',
                'value':[
                    {'n':'近期热度','v':'T'},
                    {'n':'首播时间','v':'R'},
                    {'n':'高分优先','v':'S'}
                ]
            },
            {
                'key':'年代',
                'name':'年代',
                'value':[{'n':'全部年代','v':''}] + [{'n':str(i), 'v':str(i)} for i in range(int(time.localtime().tm_year), 2018, -1)] + [
                    {'n':'2010年代','v':'2010年代'},
                    {'n':'2000年代','v':'2000年代'},
                    {'n':'90年代','v':'90年代'},
                    {'n':'80年代','v':'80年代'},
                    {'n':'70年代','v':'70年代'},
                    {'n':'60年代','v':'60年代'},
                    {'n':'更早','v':'更早'}
                ]
            },
            {
                'key':'平台',
                'name':'平台',
                'value':[{'n':'全部','v':''}] + [{'n': i, 'v': i} for i in '腾讯视频#爱奇艺#优酷#湖南卫视#Netflix#HBO#BBC#NHK#CBS#NBC#tvN'.split('#')]
            }
        ],
        'rank_list_movie':[
            {
                'key':'榜单',
                'name':'榜单',
                'value':[
                    {'n':'实时热门电影','v':'movie_real_time_hotest'},
                    {'n':'一周口碑电影榜','v':'movie_weekly_best'},
                    {'n':'豆瓣电影Top250','v':'movie_top250'}
                ]
            }
        ],
        'rank_list_tv':[
            {
                'key':'榜单',
                'name':'榜单',
                'value':[
                    {'n':'实时热门电视','v':'tv_real_time_hotest'},
                    {'n':'华语口碑剧集榜','v':'tv_chinese_best_weekly'},
                    {'n':'全球口碑剧集榜','v':'tv_global_best_weekly'},
                    {'n':'国内口碑综艺榜','v':'show_chinese_best_weekly'},
                    {'n':'国外口碑综艺榜','v':'show_global_best_weekly'}
                ]
            }
        ]
    }

    def getName(self):
        return self.site_name

    def init(self, extend=""):
        pass

    def isVideoFormat(self, url):
        pass

    def manualVideoCheck(self):
        pass

    def destroy(self):
        pass

    def homeContent(self, filter):
        result = {'class': self.classes}
        if filter:
            result['filters'] = self.filters
        return result

    def homeVideoContent(self):
        types = ('movie', 'tv')
        root = self.fetch(
            "{0}/subject_collection/subject_real_time_hotest/items?apikey={1}".format(self.douban_api_host, self.miniapp_apikey),
            headers=self.header,
        ).json()['subject_collection_items']
        videos = []
        for vod in root:
            if vod['type'] not in types:
                continue
            videos.append({
                #"vod_id": 'msearch:{}'.format(vod['title']),
                "vod_name": vod['title'],
                "vod_pic": vod['pic']['normal'] + self.img_source,
                "vod_remarks": vod['rating']['value'] if vod.get('rating') else "暂无评分"
            })
        result = {
            'list': videos
        }
        return result

    def categoryContent(self, tid, pg, filter, extend):
        pg = int(pg)
        tags = []
        if tid == "hot_gaia":
            sort = extend.get('sort', 'recommend')
            area = extend.get('area', '全部')
            path = "/movie/" + tid
            params = {
                'area': area,
                'sort': sort,
                'start': (pg - 1) * self.count,
                'count': self.count
            }
        elif tid in ("tv_hot", "show_hot"):
            stype = extend.get('type', tid)
            path = "/subject_collection/" + stype + "/items"
            params = {
                'start': (pg - 1) * self.count,
                'count': self.count
            }
        elif tid.startswith("rank_list"):
            rank_type = "movie_real_time_hotest" if tid == "rank_list_movie" else "tv_real_time_hotest"
            rank_type = extend.get('榜单', rank_type)
            path = "/subject_collection/" + rank_type + "/items"
            params = {
                'start': (pg - 1) * self.count,
                'count': self.count
            }
        else:
            path = "/" + tid + "/recommend"
            sort = 'T'
            for k in extend.keys():
                if k == 'sort':
                    sort = extend[k]
                    continue
                if len(extend[k].strip()) > 0:
                    tags.append(extend[k].strip())
            if tid == "movie":
                selected_categories = {
                    "类型": extend.get('类型', ''),
                    "地区": extend.get('地区', '')
                }
            else:
                selected_categories = {
                    "类型": extend.get('类型', ''),
                    "形式": extend.get('类型', '') + '地区' if len(extend.get('类型', '')) > 0 else '',
                    "地区": extend.get('地区', '')
                }
            params = {
                'tags': ','.join(tags),
                'sort': sort,
                'refresh': 0,
                'selected_categories': json.dumps(selected_categories, ensure_ascii=False, separators=(',',':')),
                'start': (pg - 1) * self.count,
                'count': self.count
            }

        result = {}
        url = '{0}{1}?apikey={2}&{3}'.format(self.douban_api_host, path, self.miniapp_apikey, urlencode(params))
        #print(url)
        rsp = self.fetch(url, headers=self.header)
        root = rsp.json()
        #print(root)
        videos = []
        items = root.get('subject_collection_items') if root.get('subject_collection_items') else root.get('items')
        for item in items:
            if item['type'] in ('movie', 'tv'):
                rating = item['rating']['value'] if item.get('rating') else "暂无评分"
                title = item.get('title', '')
                honor_lst = item.get('honor_infos', [])
                honor = '|'.join([it['title'] for it in honor_lst])
                vod = {
                    #'vod_id': '{0}${1}'.format(item['type'], item['id']),
                    #'vod_id': 'msearch:{}'.format(title),
                    'vod_name': title,
                    'vod_pic': item['pic']['normal'] + self.img_source,
                    'vod_remarks': '{0} {1}'.format(rating, honor).strip()
                }
                videos.append(vod)
        result['list'] = videos
        result['page'] = pg
        result['pagecount'] = math.ceil(root['total']/root['count'])
        result['limit'] = root['count']
        result['total'] = root['total']
        if tid in ('movie', 'tv') and pg == 1 and len(tags) == 0 and result['pagecount'] < 2:
            result['pagecount'] = 2
        return result

    def detailContent(self, ids):
        return {'list':[]}

    def searchContent(self, key, quick, pg='1'):
        return {'list':[]}

    def playerContent(self, flag, id, vipFlags):
        return {'parse': 0, 'url': id, 'header': self.header}

    def localProxy(self, param):
        pass
